package edu.chl.jadetalk.db;

import edu.chl.jadetalk.core.Comment;
import edu.chl.jadetalk.core.Image;
import edu.chl.jadetalk.core.Rating;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author Daniel
 */
@Stateless
public class ImageFacade implements IImageFacade {

    @PersistenceContext(unitName = "jadetalk_pu")
    private EntityManager em;

    @Override
    public void create(Image image) {
        em.persist(image);
    }

    @Override
    public void edit(Image image) {
        em.merge(image);
    }

    @Override
    public void remove(Image image) {
        em.remove(em.merge(image));
    }

    @Override
    public Image find(Object id) {
		if(id == null)
			return null;
		Image img = em.find(Image.class, id);
		em.refresh(img);
		em.refresh(img.getCommentThread());
		return img;
    }

    @Override
    public void addComment(Image image, Comment comment){
        image.getCommentThread().getComments().add(comment);
        em.merge(image.getCommentThread());
    }
    
    @Override
    public void addRating(Image image, Rating rating) {
        image.getRatings().add(rating);
        em.merge(image);
    }
    
    /**
     * Returns all 
     * @return 
     */
    @Override
    public List<Image> findAll() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery(Image.class);
        cq.select(cq.from(Image.class));
        return em.createQuery(cq).getResultList();
    }

    @Override
    public List<Image> findRange(int[] range) {
        CriteriaQuery<Image> cq = em.getCriteriaBuilder().createQuery(Image.class);
        cq.select(cq.from(Image.class));
        TypedQuery<Image> q = em.createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    @Override
    public int count() {
        CriteriaQuery<Long> cq = em.getCriteriaBuilder().createQuery(Long.class);
        Root<Image> rt = cq.from(Image.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        TypedQuery<Long> q = em.createQuery(cq);
        return (q.getSingleResult()).intValue();
    }

    /**
     * For testing purposes.
     * @param em 
     */
    void setEm(EntityManager em) {
        this.em = em;
    }
}
